<template>
  <div class="blog-edit-page">

    <!-- 顶部标题 -->
    <div class="blog-top-box">
      <input v-model="title" class="blog-title" type="text" placeholder="输入标题..."/>
      <div class="blog-top-right">
        <div class="blog-save-btn" v-if="showDraftBtn" @click="saveDraft()">保存草稿</div>
        <div class="blog-submit" @click="showAddBlog = true">{{this.id? "保存文章":"发布文章"}}</div>
      </div>
    </div>

    <!-- 发布弹窗 -->
    <add-blog :show="showAddBlog" :blogStatusInfo="blogStatusInfo" @close="showAddBlog = false" @commit="saveBlog"/>

    <!-- 博客编辑区 -->
    <client-only>
      <mavon-editor 
        ref="md"
        style="height: calc(100vh - 80px); width: 100vw;"
        :tabSize="4"
        :ishljs="true"
        :toolbars="toolbars"
        :externalLink="externalLink"
        v-model="blogContent" 
        @imgAdd="imgAdd"/>
    </client-only>
  </div>
</template>

<script>
import Api from "@/utils/api.js";
import AddBlog from '@/components/AddBlog.vue'
import OssUtils from "@/utils/ossUtils.js"
import LocalStorage from "@/utils/localStorage.js"

export default {

  head () {
    return {
      title: `编辑`,
      meta:[
        // 阻止搜索引擎编入索引
        { name:'robots',content: 'noindex'}
      ]
    }
  },

  components:{
    AddBlog
  },

  data(){
    return{
      // 发布博客弹窗
      showAddBlog: false,

      // 是否显示保存草稿按钮
      showDraftBtn: false,

      id:'',
      title:'',
      blogContent:'',

      // 文章发布状态信息
      blogStatusInfo:{
        blogStatus : '',
        openStatus : '',
        priCode : '',
        tagId: ''
      },

      userInfo:{
        userImage: "",
        userName:'',
        userId:""
      },

      externalLink: {
        markdown_css() {return 'https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.1.0/github-markdown-light.min.css';},
        hljs_js() {return 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/highlight.min.js'},
        hljs_css(css) {return 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/styles/github.min.css'},
        hljs_lang(lang) { return 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/languages/' + lang + '.min.js'},
        katex_css() {return 'https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.15.1/katex.min.css'},
        katex_js() {return 'https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.15.1/katex.min.js'},
      },

      toolbars:{
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: false, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: false, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: false, // 单双栏模式
        preview: true, // 预览
      },
    }
  },

  mounted() {
    this.$nextTick(() => {
      this.openEditTip()
      this.id = this.$route.query.id
      this.userInfo = LocalStorage.getItem("USER_INFO")
      if(this.id){
        this.getDetail();
      }else{
        // 内容初始化
        this.showDraftBtn = true
      }
    })
  },  

  methods:{
    
    // 开启编辑提示
    openEditTip(){
      window.onbeforeunload = event => {
          event.returnValue = "内容未保存，确定要关闭吗？";
      }
    },

    // 关闭编辑提示
    closeEditTip(){
      window.onbeforeunload = {
      }
    },

    getDetail(){
      // 获取详情
      this.$axios.post(Api.BLOG_DETAIL_MS,{ id: this.id})
      .then(res => {
        this.title = res.title
        this.blogContent = res.content
        this.blogStatusInfo.blogStatus = res.blogStatus
        this.blogStatusInfo.openStatus = res.openStatus
        this.blogStatusInfo.priCode = res.priCode
        this.blogStatusInfo.tagId = res.tagId

        if(res.blogStatus == 1){
          this.showDraftBtn = false
        }
      }).catch(res => {
        this.id = ''
        this.showDraftBtn = true
        this.$message.warning(res.message);
      })
    },

    imgAdd(pos, imageFile){
      let key = "blogDetail/" + this.userInfo.userId + "/" + new Date().getTime() + imageFile.name
      OssUtils.upImage(this, key, imageFile, {
        error: res => { this.$message.error(res);},
        
        success: _ => {
          this.$refs.md.$img2Url(pos, "https://img.huiyong.online/" + key);
        },
        
        progress: progress => {}
      })
    },    

    // 保存草稿
    saveDraft(){
      this.blogStatusInfo = {
        blogStatus : 0,
        openStatus : '',
        priCode : '',
        tagId: ''
      }
      this.addBlog()
    },

    // 发布文章
    saveBlog(res){
      this.blogStatusInfo = {
        blogStatus : 1,
        openStatus : res.openStatus,
        priCode : res.priCode,
        tagId: res.tagId
      }
      this.addBlog()
    },

    // 新增博客
    addBlog(){
      this.$axios.post( this.id ? Api.BLOG_EDIT : Api.BLOG_ADD, {
        id : this.id,
        title : this.title,
        content : this.blogContent,
        html: this.blogHtml,
        openStatus : this.blogStatusInfo.openStatus,
        priCode : this.blogStatusInfo.priCode,
        blogStatus : this.blogStatusInfo.blogStatus,
        tagId : this.blogStatusInfo.tagId,
      }).then( _ => {
        this.$message.success( this.blogStatusInfo.blogStatus == 0 ? "保存草稿成功！" : this.id ? "修改成功！" : "发布成功！");
        this.showAddBlog = false
        this.closeEditTip();
        // 跳转到博客详情页
        window.location.replace('/blogDetail?tagId='+ this.blogStatusInfo.tagId);
      }).catch(res => {
        this.$message.warning(res.message);
      })
    },
  },
}
</script>

<style lang="less">
@import './index.less';
@import 'mavon-editor/dist/css/index.css';
</style>

<style lang="less">
// 禁用默认样式
.hljs {
  color: none !important; 
  background: none !important;
}

.markdown-body{
  font-size: 14px !important;
}

// h1标题 大小调整
.markdown-body h1 {
  font-size: 1.6em !important;
}

.markdown-body h1, 
.markdown-body h2, 
.markdown-body h3 {
  border-bottom: none !important;
}
</style>
